package test;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Rectangle;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;

public class Main {

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createFrame().setVisible(true);
			}
		});
	}

	static JFrame createFrame() {
		JFrame frame = new JFrame("table-test");
		frame.getContentPane().add(createPanel());
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Rectangle bounds = frame.getGraphicsConfiguration().getBounds();
		bounds.width /= 2;
		bounds.height /= 2;
		bounds.x += bounds.width / 2;
		bounds.y += bounds.height / 2;
		frame.setBounds(bounds);
		return frame;
	}

	static JPanel createPanel() {
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout(10, 10));
		panel.add(new JScrollPane(createTable()));
		return panel;
	}

	static JTable createTable() {
		JTable table = new JTable();
		TableModelEx model = createModel();
		table.setModel(model);
		ListSelectionModel lsm = new DefaultListSelectionModel();
		lsm.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		table.setSelectionModel(lsm);
		table.setDefaultEditor(Object.class, createTableCellEditor());
		return table;
	}

	static TableModelEx createModel() {
		return new MyTableModel(10, 2);
	}

	static TableCellEditor createTableCellEditor() {
		JComboBox<Object> combo = new JComboBox<Object>();
		combo.setEditable(true);
		return new DefaultCellEditor(combo) {
			@Override
			public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
				TableModel model = table.getModel();
				if (model instanceof TableModelEx) {
					TableModelEx modelex = (TableModelEx) model;
					((JComboBox<Object>) editorComponent).setModel(new DefaultComboBoxModel<Object>(modelex.getCandidatesAt(row, column)));
				}
				return super.getTableCellEditorComponent(table, value, isSelected, row, column);
			}
			
		};
	}
}
